package com.oot.twitter;
import android.content.SharedPreferences;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.google.android.gcm.GCMRegistrar;
import com.lazylist.ImageLoader;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import com.markupartist.android.widget.*;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.oot.twitter.Tweets.TweetItem;
import com.oot.twitter.adapter.TweetsListAdapter;
import com.oot.twitter.base.SimpleURI;
import com.oot.twitter.info.TJSonParser;
import com.oot.twitter.info.Tweet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.support.v4.app.NavUtils;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.OnScrollListener;

public class Twitter extends Activity implements OnClickListener {

	ViewGroup parent;
	LinearLayout twitter_home,twitter_connect,twitter_discover,twitter_me;
	LinearLayout twitter_search,twitter_new_tweet;
	ImageView image_tab_home,image_tab_connect,image_tab_discover,image_tab_me;
	TextView text_home,text_connect,text_discover,text_me;
	
	public ArrayList<TweetItem> m_tweet_item =null;
	public TimeLineListAdapter m_adapter;
	
	private ArrayList<Tweet> tweets;
	
	PullToRefreshListView list;
	
	int old = 0;
	
	int item_position_clicked = -1;
	
	boolean loading = true;
	
	View footerView;
	ProgressBar progress;
	
    int old_post = -1,curret_postion = -1;
	
    boolean on_scroll = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_twitter);
        
        GlobalData.imageLoader = new ImageLoader(this);
        
        twitter_home = (LinearLayout)findViewById(R.id.twitter_home);
        twitter_connect = (LinearLayout)findViewById(R.id.twitter_connect);
        twitter_discover = (LinearLayout)findViewById(R.id.twitter_discover);
        twitter_me = (LinearLayout)findViewById(R.id.twitter_me);
        twitter_search = (LinearLayout)findViewById(R.id.twitter_search);
        twitter_new_tweet = (LinearLayout)findViewById(R.id.twitter_new_tweet);
        
        
        
        twitter_home.setOnClickListener(this);
        twitter_connect.setOnClickListener(this);
        twitter_discover.setOnClickListener(this);
        twitter_me.setOnClickListener(this);
        twitter_search.setOnClickListener(this);
        twitter_new_tweet.setOnClickListener(this);
        
        image_tab_home = (ImageView)findViewById(R.id.image_tab_home);
        image_tab_connect = (ImageView)findViewById(R.id.image_tab_connect);
        image_tab_discover = (ImageView)findViewById(R.id.image_tab_discover);
        image_tab_me = (ImageView)findViewById(R.id.image_tab_me);
        
        text_home = (TextView)findViewById(R.id.text_tab_home);
        text_connect = (TextView)findViewById(R.id.text_tab_connect);
        text_discover = (TextView)findViewById(R.id.text_tab_discover);
        text_me = (TextView)findViewById(R.id.text_tab_me);
        
        
        getUserID();
        initializeUI();


		// Get Google Clound RegID
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			GCMRegistrar.register(this, "507076552906");
		} else {
			Log.v("Main Activity", "Already registered");
		}

    }
    
    @Override
    protected void onResume()
    {
    	super.onResume();
    	System.out.println("OnResume Called !!!");
    	m_adapter.notifyDataSetChanged();
    }    
    
    public void initializeUI() //Initialize UI and Data
    {
    	parent = (ViewGroup)findViewById(R.id.tabbar);
    	parent.removeAllViews();
    	View v = LayoutInflater.from(getBaseContext()).inflate(R.layout.twitter_home_layout, parent, true);
    	
    	//Get data from Server
    	StringBuilder builder = new StringBuilder();
    	
    	HttpGet httpPost = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline");
    	try{
    			HttpResponse response = GlobalData.client.execute(httpPost);
    			StatusLine statusLine = response.getStatusLine();
    		
    			int statusCode = statusLine.getStatusCode();
    			if (statusCode == 200) {
    				HttpEntity entity = response.getEntity();
    				InputStream content = entity.getContent();
    				BufferedReader reader = new BufferedReader(
    						new InputStreamReader(content));
    				String line;
    				while ((line = reader.readLine()) != null) {
    					builder.append(line);
    				}
    			} else {
    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
    			}			
    		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}					
		
    	//System.out.println("RETURN|"+builder.toString());    	
    	
    	
    	m_tweet_item = new ArrayList<TweetItem>();
    	
    	try{
    		JSONArray jsonArray = new JSONArray(builder.toString());
    		//System.out.println("Length = "+jsonArray.length());
    		for(int i = 0;i < jsonArray.length(); i++)
    		{
    			JSONObject jsonObject = jsonArray.getJSONObject(i);
    			Bitmap bitmap = null;
    			//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
   			 	try {
   			 		bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
   			 	if(i == 0)
   			 		GlobalData.timeline_maxid = jsonObject.getInt("tweet_id");
   			 	if(i == jsonArray.length() - 1)
   			 		GlobalData.timeline_sinceid = jsonObject.getInt("tweet_id");
   			 	
   			 	
    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("parent_id"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
    			if(GlobalData.user_id.equals(jsonObject.getString("user_id")))
    				tweet_item.setMyseft(true);
    			m_tweet_item.add(tweet_item);
    		}
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	
    	//System.out.println("MIN ID = "+ GlobalData.timeline_sinceid);
    	
    	this.m_adapter = new TimeLineListAdapter(this, R.layout.tweet_item, m_tweet_item);
        list = (PullToRefreshListView)v.findViewById(R.id.timeline_list);
        list.setAdapter(m_adapter);
    	setListEventHandler();

    }    
    
    //////////////  SET LIST EVENT HANDLER /////////////////
    public void setListEventHandler()
    {
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footerlistview, null, false);
        list.addFooterView(footerView);
        progress = (ProgressBar)findViewById(R.id.progressbar_more); 
        
        list.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh() {
                // Do work to refresh the list here.
            	new GetNewData().execute(new String[]{"ABCD"});
            	m_adapter.notifyDataSetChanged();
            }
        });
    	list.setAdapter(m_adapter);  
    	
    	///////////////////// ITEM CLICK EVENT ////////////////////////////
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int postion, long l) {
                // Prepare param
                //tweet_id, content, created_time, parent_id, user_id, username, full_name, avatar, refav, retweeted_by;
            	System.out.println("OOT|"+postion+"|"+m_tweet_item.get(postion).getContent());
            	if(postion != old_post)
            	{
            		item_position_clicked = postion;
            		Tweet tweet = new Tweet();
            		tweet.setContent(m_tweet_item.get(postion - 1).getContent());
            		tweet.setFull_name(m_tweet_item.get(postion -1).getFullname());
            		tweet.setRefav(m_tweet_item.get(postion -1).getRefav());
            		tweet.setTweet_id(m_tweet_item.get(postion -1).getID());

            		tweet.setCreated_time(m_tweet_item.get(postion -1).getCreatedTime());
            		tweet.setParent_id(m_tweet_item.get(postion -1).getParentID());
            		tweet.setAvatar(m_tweet_item.get(postion -1).getAvatar());
            		tweet.setUsername(m_tweet_item.get(postion -1).getUsername());
            		GlobalData.paramIntent = tweet;
                
            		Intent tweetInfo = new Intent(Twitter.this, TweetInfo.class);
            		startActivityForResult(tweetInfo, 0);
            	}
            }
        });
        
        
        ///////////////////////////////////////////////////////////////////
        ///////////////////// ITEM LONG CLICK EVENT ///////////////////////
        ////////////////////////////////////////////////////////////////////
        list.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long l) {
				// TODO Auto-generated method stub
				curret_postion = position;
				if(old_post != -1)
				{
					m_tweet_item.get(old_post -1).setIsLongClick(false);
					m_adapter.notifyDataSetChanged();
				}
				LinearLayout onlayout = (LinearLayout)view.findViewById(R.id.timeline_mainparent);
				m_tweet_item.get(position -1).setHeight(onlayout.getHeight());
				
				m_tweet_item.get(position -1).setIsLongClick(true);
				m_adapter.notifyDataSetChanged();
				
				old_post = position;

				return true;				

			}
        	
		});
    	
        
        ///////////////////////////////////////////////////////////////////////////
        /////////////////////// LOAD MORE TWEET HANDLER ///////////////////////////
        ///////////////////////////////////////////////////////////////////////////
    	list.setOnScrollListener(new OnScrollListener() {	//Load More item when endless scroll	
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
				boolean loadmore = (firstVisibleItem + visibleItemCount >= totalItemCount);
				if(loadmore && GlobalData.isGetMore && loading)
				{
						//System.out.println("GET MORE ITEM");					
						Thread thread = new Thread(null,loadMoreListItems);
						thread.start();
				}

			}
		});    	
    	
    	
    }
    
    
    ArrayList<TweetItem> more;
    private Runnable loadMoreListItems = new Runnable() {
		public void run() {
			// TODO Auto-generated method stub
			GlobalData.isGetMore = false;
			more = new ArrayList<TweetItem>();
	    	StringBuilder builder = new StringBuilder();    	
	    	HttpGet httpPost = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline?since_id="+GlobalData.timeline_sinceid);
	    	
	    	//System.out.println(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline?since_id="+GlobalData.timeline_sinceid);
	    	try{
	    			HttpResponse response = GlobalData.client.execute(httpPost);
	    			StatusLine statusLine = response.getStatusLine();	
	    			int statusCode = statusLine.getStatusCode();
	    			if (statusCode == 200) {
	    				HttpEntity entity = response.getEntity();
	    				InputStream content = entity.getContent();
	    				BufferedReader reader = new BufferedReader(
	    						new InputStreamReader(content));
	    				String line;
	    				while ((line = reader.readLine()) != null) {
	    					builder.append(line);
	    				}
	    			} else {
	    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
	    			}			
	    		
	    	}catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}	
	    	
	    	if(builder.toString().length()>5)
	    	{
	    		try{
	    			JSONArray jsonArray = new JSONArray(builder.toString());
	    			//System.out.println("MORE LENGTH = "+jsonArray.length());
	    			for(int i = 0;i < jsonArray.length(); i++)
	    			{
	    				JSONObject jsonObject = jsonArray.getJSONObject(i);
	    				Bitmap bitmap = null;
	    				//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
	   			 		try {
	   			 			bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
	   			 		} catch (MalformedURLException e) {
	   			 			// TODO Auto-generated catch block
	   			 			e.printStackTrace();
	   			 		} catch (IOException e) {
	   			 			// TODO Auto-generated catch block
	   			 			e.printStackTrace();
	   			 		}
	   			 		
	   			 		if( i == jsonArray.length() - 1)
	   			 		{
	   			 			old = GlobalData.timeline_sinceid;
	   			 			GlobalData.timeline_sinceid = jsonObject.getInt("tweet_id");
	   			 		}
	   			 	
	 
	   	    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("parent_id"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
	   	    			if(GlobalData.user_id.equals(jsonObject.getString("user_id")))
	   	    				tweet_item.setMyseft(true);
	   			 		more.add(tweet_item);
	    			}
	    		}
	    		catch(Exception e)
	    		{
	    			e.printStackTrace();
	    		}
	    	}
	    	else
	    	{
	    		//System.out.println("Hahahahaha");
	    		loading = false;
	    		progress.setVisibility(View.INVISIBLE);
	    		GlobalData.isGetMore = false;
	    	}	
	    	
		    //System.out.println("SINCE ID 2 = "+GlobalData.timeline_sinceid+"|OLD="+old);
	    	runOnUiThread(returnRes);
	    	
		}
	};
	private Runnable returnRes = new Runnable() {		
		public void run() {
			// TODO Auto-generated method stub
			if(more != null && more.size()>0)
			{
				for(int i = 0; i< more.size(); i++)
				{
					m_tweet_item.add(more.get(i));
				}
			}

			m_adapter.notifyDataSetChanged();
			list.onRefreshComplete();
			GlobalData.isGetMore = true;
		}
	};
	
	
    public void getMoreData()
    {
    	StringBuilder builder = new StringBuilder();
    	
    	HttpGet httpPost = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline?since_id="+GlobalData.timeline_sinceid);
    	try{
    			HttpResponse response = GlobalData.client.execute(httpPost);
    			StatusLine statusLine = response.getStatusLine();
    		
    			int statusCode = statusLine.getStatusCode();
    			if (statusCode == 200) {
    				HttpEntity entity = response.getEntity();
    				InputStream content = entity.getContent();
    				BufferedReader reader = new BufferedReader(
    						new InputStreamReader(content));
    				String line;
    				while ((line = reader.readLine()) != null) {
    					builder.append(line);
    				}
    			} else {
    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
    			}			
    		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}		
    	//System.out.println(builder.toString());

    	if(builder.toString().length()>3)
    	{
    		try{
    			JSONArray jsonArray = new JSONArray(builder.toString());
    			System.out.println("Length More = "+jsonArray.length());
    			for(int i = 0;i < jsonArray.length(); i++)
    			{
    				JSONObject jsonObject = jsonArray.getJSONObject(i);
    				Bitmap bitmap = null;
    				//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
   			 		try {
   			 			bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
   			 		} catch (MalformedURLException e) {
   			 			// TODO Auto-generated catch block
   			 			e.printStackTrace();
   			 		} catch (IOException e) {
   			 			// TODO Auto-generated catch block
   			 			e.printStackTrace();
   			 		}
   			 		if( i == jsonArray.length() - 1)
   			 			GlobalData.timeline_sinceid = jsonObject.getInt("tweet_id");
   			 	
   			 		//System.out.println("SINCE ID = "+GlobalData.timeline_sinceid);
   			 	
   	    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("parent_id"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
   	    			if(GlobalData.user_id.equals(jsonObject.getString("user_id")))
   	    				tweet_item.setMyseft(true);;
   	    					
   			 		m_tweet_item.add(tweet_item);
    			

    			}
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    	else
    	{
    		GlobalData.isGetMore = false;
    		//System.out.println("END LIST");
    	}
    	
    }
    
    
    public void getUserID()
    {
		StringBuilder builder = new StringBuilder();
		HttpPost httpPost = new HttpPost(ConnectionTwitter.SERVER_URL+"api/site/getCurrentUserID");
		
    	try{
    		HttpResponse response = GlobalData.client.execute(httpPost);
    		StatusLine statusLine = response.getStatusLine();
    		
    		int statusCode = statusLine.getStatusCode();
    		

    			HttpEntity entity = response.getEntity();
    			InputStream content = entity.getContent();
    			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    			String line;
    			while((line= reader.readLine())!= null)
    			{
    				builder.append(line);			
    			}				
    		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}					
		
    	GlobalData.user_id = builder.toString().trim();
    	//System.out.println(builder.toString());		    	
    	
    }
    
    //On Mouse Click Event Handler
    public void onClick(View v) {
		switch(v.getId())
		{
			case R.id.twitter_home:		
				image_tab_home.setImageResource(R.drawable.ic_tab_home_selected);
				image_tab_connect.setImageResource(R.drawable.ic_tab_connect_default);
				image_tab_discover.setImageResource(R.drawable.ic_tab_discover_default);
				image_tab_me.setImageResource(R.drawable.ic_tab_me_default);
				
		    	parent = (ViewGroup)findViewById(R.id.tabbar);
		    	parent.removeAllViews();
		    	View v1 = LayoutInflater.from(getBaseContext()).inflate(R.layout.twitter_home_layout, parent, true);	
		    	
		    	GlobalData.isGetMore = true;
		    	loading = true;
		    	list = (PullToRefreshListView)v1.findViewById(R.id.timeline_list);
		    	list.setAdapter(m_adapter);
		    	
		    	setListEventHandler();
		    	
				break;
			case R.id.twitter_connect:
				image_tab_home.setImageResource(R.drawable.ic_tab_home_default);
				image_tab_connect.setImageResource(R.drawable.ic_tab_connect_selected);
				image_tab_discover.setImageResource(R.drawable.ic_tab_discover_default);
				image_tab_me.setImageResource(R.drawable.ic_tab_me_default);	
				
		    	parent = (ViewGroup)findViewById(R.id.tabbar);
		    	parent.removeAllViews();				
				View v2 = LayoutInflater.from(getBaseContext()).inflate(R.layout.twitter_connect_layout, parent, true);	
				
				final Button btnInteractions = (Button)v2.findViewById(R.id.btnTabInteractions);
				final Button btnMentions = (Button)v2.findViewById(R.id.btnTabMentions);
				
				btnInteractions.setOnClickListener(new OnClickListener() {				
					public void onClick(View v) {
						// TODO Auto-generated method stub
						btnInteractions.setBackgroundResource(R.drawable.btn_segmented_selected);
						btnMentions.setBackgroundResource(R.drawable.btn_segmented_default);
					}
				});
				
				btnMentions.setOnClickListener(new OnClickListener() {					
					public void onClick(View v) {
						// TODO Auto-generated method stub
						btnInteractions.setBackgroundResource(R.drawable.btn_segmented_default);
						btnMentions.setBackgroundResource(R.drawable.btn_segmented_selected);						
					}
				});
				
				break;
				
			case R.id.twitter_discover:
				image_tab_home.setImageResource(R.drawable.ic_tab_home_default);
			    image_tab_connect.setImageResource(R.drawable.ic_tab_connect_default);
			    image_tab_discover.setImageResource(R.drawable.ic_tab_discover_selected);
			    image_tab_me.setImageResource(R.drawable.ic_tab_me_default);
			    
			    parent = (ViewGroup)findViewById(R.id.tabbar);
			       parent.removeAllViews();
			    LayoutInflater.from(getBaseContext()).inflate(R.layout.twitter_discovery_layout, parent, true);
			    
			    JSONArray discovery = ConnectionTwitter.sendRequestJSonArray(ConnectionTwitter.DISCOVERY, null);
			    if (discovery != null) {
			     tweets = new ArrayList<Tweet>();
			     try {
			      for (int i = 0; i < discovery.length(); i++) {
			        tweets.add(new Tweet(discovery.getJSONObject(i)));
			      }
			     } catch (Exception e) {
			      System.out.println("Error in loop parse tweets list");
			      return;
			     }
			     
			     TweetsListAdapter adapter = new TweetsListAdapter(this, R.layout.tweet, tweets);
			     ListView discovery_list = (ListView)findViewById(R.id.discovery_list);
			     discovery_list.setAdapter(adapter);
			     discovery_list.setOnItemClickListener(new OnItemClickListener() {
			    	 
			      public void onItemClick(AdapterView<?> tweetAdapter, View arg1,int position, long arg3) {
			       Intent tweetInfo = new Intent(Twitter.this, TweetInfo.class);
			       GlobalData.paramIntent = (Tweet)tweetAdapter.getItemAtPosition(position);
			       startActivity(tweetInfo);
			      }
			     });
			    }
			    break;
				
			case R.id.twitter_me:
				
				
				image_tab_home.setImageResource(R.drawable.ic_tab_home_default);
				image_tab_connect.setImageResource(R.drawable.ic_tab_connect_default);
				image_tab_discover.setImageResource(R.drawable.ic_tab_discover_default);
				image_tab_me.setImageResource(R.drawable.ic_tab_me_selected);	
				
		    	parent = (ViewGroup)findViewById(R.id.tabbar);
		    	parent.removeAllViews();
		    	View v4 = LayoutInflater.from(getBaseContext()).inflate(R.layout.twitter_me_layout, parent, true);	
		    	
		    	//Get data from API service
		    	StringBuilder return_value = new StringBuilder();
		    	HttpGet httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/user/show");
		    	try{
		    		HttpResponse response = GlobalData.client.execute(httpGet);
		    		StatusLine statusLine = response.getStatusLine();
	    			HttpEntity entity = response.getEntity();
	    			InputStream content = entity.getContent();
	    			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	    			String line;
	    			while((line= reader.readLine())!= null)
	    			{
	    				return_value.append(line);			
	    			}			    		
		    		
		    	}
		    	catch(Exception e)
		    	{
		    		e.printStackTrace();
		    	}
		    	String jsonvalue = return_value.toString();
		    	jsonvalue = "["+return_value+"]";
		    	System.out.println(jsonvalue);
		    	
		    	try{
		    		JSONArray json = new JSONArray(jsonvalue);
		    		JSONObject obj = json.getJSONObject(0);
		    		GlobalData.user_id = obj.getString("user_id");
		    		GlobalData.username = obj.getString("username");
		    		GlobalData.fullname = obj.getString("full_name");
		    		GlobalData.avarta = BitmapFactory.decodeStream((InputStream)new URL(obj.getString("avatar")).getContent());
		    		GlobalData.follower = obj.getString("followers_count");
		    		GlobalData.following = obj.getString("following_count");
		    		GlobalData.tweets = obj.getString("tweets_count");
		    		GlobalData.bio = obj.getString("bio");
		    		GlobalData.website = obj.getString("website");
		    		GlobalData.location = obj.getString("location");
		    		//System.out.println("CHANCHANCHANCHAN|"+obj.get("avatar"));
		    	}
		    	catch (Exception e) {
					// TODO: handle exception
		    		e.printStackTrace();
				}
		    	TextView myname = (TextView)v4.findViewById(R.id.user_name);
		    	TextView me_tweets = (TextView)v4.findViewById(R.id.me_tweets);
		    	TextView me_following = (TextView)v4.findViewById(R.id.me_following);
		    	TextView me_follower = (TextView)v4.findViewById(R.id.me_follower);
		    	ImageView me_avarta = (ImageView)v4.findViewById(R.id.me_avarta);
		    	
		    	myname.setText(GlobalData.fullname);
		    	me_tweets.setText(GlobalData.tweets);
		    	me_following.setText(GlobalData.following);
		    	me_follower.setText(GlobalData.follower);
		    	me_avarta.setImageBitmap(ImageHelper.getRoundedCornerBitmap(GlobalData.avarta, 5));
		    	
		    	LinearLayout tweets_layout = (LinearLayout)v4.findViewById(R.id.me_tweets_layout);
		    	LinearLayout following_layout = (LinearLayout)v4.findViewById(R.id.me_following_layout);
		    	LinearLayout follower_layout = (LinearLayout)v4.findViewById(R.id.me_follower_layout);

		    	tweets_layout.setOnClickListener(this);
		    	following_layout.setOnClickListener(this);
		    	follower_layout.setOnClickListener(this);
		    	
		    	LinearLayout twitter_me_detail = (LinearLayout)v4.findViewById(R.id.twitter_me_detail);
		    	twitter_me_detail.setOnClickListener(this);
		    	
				break;
				
			case R.id.twitter_search:		
				
				break;
				
			case R.id.twitter_new_tweet:
				Intent i = new Intent(Twitter.this,NewTweetDialog.class);
				startActivity(i);
								
				break;
				
			case R.id.me_tweets_layout:
				Intent tweet_activity = new Intent(Twitter.this,Tweets.class);
				Bundle bun = new Bundle();
				bun.putString("user_id", GlobalData.user_id);
				bun.putString("type", "tweets");
				tweet_activity.putExtras(bun);
				startActivity(tweet_activity);
				break;
			
			case R.id.me_following_layout:
				// Prepare param
				GlobalData.paramIntent = new SimpleURI("Following",ConnectionTwitter.FOLLOWING_URL, new RequestParams());

				// Start new intent
				Intent following = new Intent(Twitter.this, UsersList.class);
				startActivity(following);
				break;
				
			case R.id.me_follower_layout:
                System.out.println("Follower here");
                // Prepare param
                GlobalData.paramIntent = new SimpleURI("Followers",ConnectionTwitter.FOLLOWER_URL, new RequestParams());;

                // Start new intent
                Intent follower = new Intent(Twitter.this, UsersList.class);
                startActivity(follower);
				break;
			case R.id.twitter_me_detail :
				Intent me_detail = new Intent(Twitter.this,OtherPersonProfile.class);
				Bundle s = new Bundle();
				s.putString("id", GlobalData.user_id);
				s.putString("username", GlobalData.username);
				s.putString("fullname", GlobalData.fullname);
				s.putString("location", GlobalData.location);
				s.putString("website", GlobalData.website);
				s.putString("bio", GlobalData.bio);			
				s.putString("tweets_count", GlobalData.tweets);
				s.putString("following_count", GlobalData.following);
				s.putString("follower_count", GlobalData.follower);
				me_detail.putExtras(s);
				me_detail.putExtra("avarta", GlobalData.avarta);
				startActivity(me_detail);				
				break;
		}
    	
	}
    
   
    ///////////////FAVORITES - UNFAVORITE/////////////////////////

    public boolean acFav(TweetItem item){
    	//Get data from Server
    	boolean return_value = false;
    	StringBuilder builder = new StringBuilder();
    	HttpPost httpPost;
    	if(item.getRefav().equals("10") || item.getRefav().equals("11"))
    	{
    		httpPost = new HttpPost(ConnectionTwitter.UNFAVORITE_URL+"?tweet_id="+item.getID());
    	}
    	else
    	{
    		httpPost = new HttpPost(ConnectionTwitter.FAVORITE_URL+"?tweet_id="+item.getID());
    	}
    	try{
			HttpResponse response = GlobalData.client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
		
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(Twitter.class.toString(), "Failed to download JSON string");
			}			
		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	
    	String result = builder.toString();
    	result = "["+result+"]";
    	try {
    		JSONArray json = new JSONArray(result);
    		JSONObject jsonObject = json.getJSONObject(0);
    		String value = jsonObject.getString("result");
    		int res = Integer.parseInt(value);
    		if(res == 1) //Update Success
    			return_value = true;
    	}catch (JSONException e){ 
    		// TODO Auto-generated catch block		    		
    		e.printStackTrace();
    	}    	
    	
    	return return_value;
	}
 
    
    
    /////////////////DESTROY TWEET /////////////////////////
    public boolean destroyTweet(TweetItem item)
    {
    	boolean return_value = false;
    	
    	StringBuilder builder = new StringBuilder();
    	HttpPost httpPost = new HttpPost(ConnectionTwitter.DESTROYTWEET+"?tweet_id="+item.getID());
    	try{
			HttpResponse response = GlobalData.client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
		
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(Twitter.class.toString(), "Failed to download JSON string");
			}			
		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}    	
    	String result = builder.toString();
    	result = "["+result+"]";
    	try {
    		JSONArray json = new JSONArray(result);
    		JSONObject jsonObject = json.getJSONObject(0);
    		String value = jsonObject.getString("result");
    		int res = Integer.parseInt(value);
    		if(res == 1) //Update Success
    			return_value = true;
    	}catch (JSONException e){ 
    		// TODO Auto-generated catch block		    		
    		e.printStackTrace();
    	}        	
    	
    	
    	return return_value;
    }
    
    private class GetNewData extends AsyncTask<String,Void,String> {//Get New Data When Pull Scroll
        @Override
        protected void onPreExecute() 
        {
        	System.out.println("MAX ID ="+GlobalData.timeline_maxid);
        }  
		@Override
		protected String doInBackground(String... params) 
		{
			// TODO Auto-generated method stub
	    	StringBuilder builder = new StringBuilder();
	    	
	    	HttpGet httpPost = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline?max_id="+GlobalData.timeline_maxid);
	    	try{
	    			HttpResponse response = GlobalData.client.execute(httpPost);
	    			StatusLine statusLine = response.getStatusLine();
	    		
	    			int statusCode = statusLine.getStatusCode();
	    			if (statusCode == 200) {
	    				HttpEntity entity = response.getEntity();
	    				InputStream content = entity.getContent();
	    				BufferedReader reader = new BufferedReader(
	    						new InputStreamReader(content));
	    				String line;
	    				while ((line = reader.readLine()) != null) {
	    					builder.append(line);
	    				}
	    			} else {
	    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
	    			}			
	    		
	    	}catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}					
	    	
	    	if(builder.toString().length()>5)
	    	{
	    	try{
	    		JSONArray jsonArray = new JSONArray(builder.toString());
	    		System.out.println("Length refresh = "+jsonArray.length());
	    		old_post+=jsonArray.length();
	    		for(int i = 0;i < jsonArray.length(); i++)
	    		{
	    			JSONObject jsonObject = jsonArray.getJSONObject(i);
	    			Bitmap bitmap = null;
	    			//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
	   			 	try {
	   			 		bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	   			 	if( i == 0)
	   			 		GlobalData.timeline_maxid = jsonObject.getInt("tweet_id");
	   			 		
	    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("parent_id"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
	    			if(GlobalData.user_id.equals(jsonObject.getString("user_id")))
	    			{
	    				tweet_item.setMyseft(true);
	    			}
	    			m_tweet_item.add(0,tweet_item);

	    		}
	    	}
	    	catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}			
	    	}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			//System.out.println("Refrested");
			m_adapter.notifyDataSetChanged();
			list.onRefreshComplete();
            super.onPostExecute("a");
        }    	 
    }    


    
    public class TweetItem{ //Descriptions Tweets item in ListView
    	public String tweet_id;
    	public String content;
    	public String created_time;
    	public String username;
    	public String fullname;
    	public Bitmap avarta_url;
    	public String avatar;
    	public String parent_id;
    	public String refav;
    	public String user_id;
    	public String retweeted_by;
    	public boolean is_longclick = false;
    	public boolean myseflt = false;
    	public int height;
    	public TweetItem(String tweet_id,String user_id,String content,String created_time,String username,String fullname,Bitmap img,String avatar,String parent_id,String refav,String retweeted_by)
    	{
    		this.tweet_id = tweet_id;
    		this.content = content;
    		this.created_time = created_time;
    		this.username = username;
    		this.fullname = fullname;
    		this.avarta_url = img;
    		this.refav = refav;
    		this.avatar = avatar;
    		this.parent_id = parent_id;
    		this.user_id = user_id;
    		this.height = 0;
    		this.retweeted_by = retweeted_by;
    	}
    	
    	public void setMyseft(boolean me)
    	{
    		this.myseflt = me;
    	}
    	public boolean isMySeft()
    	{
    		return this.myseflt;
    	}
    	public void setRefav(String refa)
    	{
    		this.refav = refa;
    	}
    	public void setIsLongClick(boolean is_long_click)
    	{
    		this.is_longclick = is_long_click;
    	}
    	public boolean isLongClick()
    	{
    		return this.is_longclick;
    	}
    	public String getUserID()
    	{
    		return this.user_id;
    	}
    	public String getID()
    	{
    		return this.tweet_id;
    	}
    	public String getContent()
    	{
    		return this.content;
    	}
    	public String getCreatedTime()
    	{
    		return this.created_time;
    	}
    	public String getUsername()
    	{
    		return this.username;
    	}
    	public String getFullname()
    	{
    		return this.fullname;
    	}
    	public Bitmap getAvarta()
    	{
    		return this.avarta_url;
    	}
    	public String getAvatar()
    	{
    		return this.avatar;
    	}
    	public String getParentID()
    	{
    		return this.parent_id;
    	}
    	public String getRefav()
    	{
    		return this.refav;
    	}
    	public int getHeight()
    	{
    		return this.height;
    	}
    	public void setHeight(int height)
    	{
    		this.height = height;
    	}
    	public String getRetweetedBy()
    	{
    		return this.retweeted_by;
    	}
    }
    
    private class TimeLineListAdapter extends ArrayAdapter<TweetItem>{ //Timeline Home List Adapter
    	private ArrayList<TweetItem> items;
    	public TimeLineListAdapter(Context context, int textViewResourceId, ArrayList<TweetItem> items)
    	{
    		super(context, textViewResourceId,items);
    		this.items = items;
    	}
    	@Override
    	public int getViewTypeCount() {
    	    return 12;
    	  }
        @Override
        public int getItemViewType(int position) {
        	String type = this.items.get(position).getRefav();
        	if(type.equals("0")) //Normal Tweets
        		return 0;
        	else if(type.equals("1")) //Retweet
        		return 1;
        	else if(type.equals("10")) //Favorites
        		return 10;
        	else   						//Retweet and Favorites
        		return 11;

        }      
        
    	@Override
    	public View getView(int position, View v, ViewGroup parent) 
    	{    
    		
    		if(v == null)
    		{
    			LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			v = vi.inflate(R.layout.tweet_item,null);
    		}
    		
    		final TweetItem tweet_item = items.get(position);
    		final int pos = position;
    		
    		if(tweet_item!= null)
    		{
    			 //Long click handler and view
    			if(tweet_item.isLongClick())
    			{
    				LinearLayout longlayout = (LinearLayout)v.findViewById(R.id.timeline_onlongclick);
    				LinearLayout onlayout = (LinearLayout)v.findViewById(R.id.timeline_mainparent);
    				
    				longlayout.setVisibility(View.VISIBLE);
    				LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, tweet_item.getHeight());
    				longlayout.setLayoutParams(param);
    				//System.out.println(tweet_item.getHeight());
    				onlayout.setVisibility(View.GONE);
    				
    				
    				LinearLayout de = (LinearLayout)v.findViewById(R.id.tweet_item_delete);
    				ImageView rt = (ImageView)v.findViewById(R.id.rtImg);
    				final ImageView fav = (ImageView)v.findViewById(R.id.faveImg);
    				ImageView rep = (ImageView)v.findViewById(R.id.replyImg);
    				ImageView retw  = (ImageView)v.findViewById(R.id.rtImg);
    				ImageView share = (ImageView)v.findViewById(R.id.tweet_item_share);
    				
    				if(tweet_item.isMySeft())
    				{
    					retw.setImageResource(R.drawable.ic_action_rt_disabled);
    					retw.setClickable(false);
    				}
    				else
    				{
    					if(tweet_item.getRefav().equals("1") || tweet_item.getRefav().equals("11"))
    					{
    						retw.setImageResource(R.drawable.ic_action_rt_on_default);
    					}
    				}
    				
    				if(tweet_item.getRefav().equals("10") || tweet_item.getRefav().equals("11"))
    				{
    					fav.setImageResource(R.drawable.ic_action_fave_on_default);
    				}
    				else
    				{
    					fav.setImageResource(R.drawable.ic_action_fave_off_default);
    				}
    				

					share.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							shareAction(tweet_item.getContent());
						}
					});
    				// Reply 
    				rep.setOnClickListener(new OnClickListener() {					
    					public void onClick(View arg0) {
    						// TODO Auto-generated method stub
    						//lay.setVisibility(View.VISIBLE);
    						//lin.setVisibility(View.GONE);	
    						m_tweet_item.get(pos).setIsLongClick(false);
    						m_adapter.notifyDataSetChanged();
    						
    						String content = m_tweet_item.get(pos).getContent();
    						String mentions = "";
    						for(int i = 0; i< content.length();i++)
    						{
    							if(content.charAt(i) == '@')
    							{
    								int j = i;
    								while(content.charAt(j) != ' ')
    								{
    									j++;
    								}
    								mentions += content.substring(i, j);
    								mentions += " "; 
    							}
    						}
    						mentions = mentions + "@"+m_tweet_item.get(pos).getUsername();
    						Intent reply_intent = new Intent(Twitter.this,NewTweetDialog.class);
    						Bundle bun = new Bundle();
    						bun.putString("mentions", mentions);
    						bun.putString("tweet_id", m_tweet_item.get(pos).getID());
    						reply_intent.putExtras(bun);
    						startActivity(reply_intent);
    						
    					}
    				});    		
    				
  				
    				//Share
					share.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							shareAction(tweet_item.getContent());
						}
					});    	    				
    				
    				// Favorite - Unfavorite
    				fav.setOnClickListener(new OnClickListener() {				
    					public void onClick(View v) {
    						// TODO Auto-generated method stub
    						if(tweet_item.getRefav().equals("10") || tweet_item.getRefav().equals("11")) //Unfavorite
    						{
    								if(acFav(tweet_item))
    								{		
    									fav.setImageResource(R.drawable.ic_action_fave_off_default);
    									if(tweet_item.getRefav().equals("10"))
    									{
    										tweet_item.setRefav("0");
    										//refav.setVisibility(View.INVISIBLE);
    									}
    									if(tweet_item.getRefav().equals("11"))
    									{
    										tweet_item.setRefav("1");
    									}
    									old_post = -1;
    									tweet_item.setIsLongClick(false);
    									m_adapter.notifyDataSetChanged();
    								}
    						}
    						else //Favorite
    						{
    								if(acFav(tweet_item))
    								{

    									//System.out.println("Favorited");
    									fav.setImageResource(R.drawable.ic_action_fave_on_default);
    									if(tweet_item.getRefav().equals("0"))
    									{
    										tweet_item.setRefav("10");
    									}
    									if(tweet_item.getRefav().equals("1"))
    									{
    										tweet_item.setRefav("11");
    									}
    									old_post = -1;
    									tweet_item.setIsLongClick(false);
    									m_adapter.notifyDataSetChanged();
    								}
    						}
    						
    					}
    					
    				});			   				

    				if(tweet_item.isMySeft()) // This tweet is myseft
    				{
    					de.setVisibility(View.VISIBLE);
    					ImageView imgDel = (ImageView)v.findViewById(R.id.delImg);
    					
    					//Delete Tweet
    					imgDel.setOnClickListener(new OnClickListener() {
    						public void onClick(View v) {
    							// TODO Auto-generated method stub
    							AlertDialog.Builder builder  = new AlertDialog.Builder(Twitter.this);
    							builder.setTitle("Delete");
    							builder.setMessage("Do you want to delete this Tweet?");
    							builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {						
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									if(destroyTweet(tweet_item))
    									{
    										m_tweet_item.remove(pos);
    										m_adapter.notifyDataSetChanged();
    										dialog.dismiss();
    									}
    								}
    							})
    							.setNegativeButton("No", new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									dialog.dismiss();
    								}
    							});
    							builder.show();
    						}
    					});
    					
    				}
    				else
    				{
    					
    					de.setVisibility(View.GONE);
    					if(tweet_item.getRefav().equals("1") || tweet_item.getRefav().equals("11"))
    						rt.setBackgroundResource(R.drawable.ic_action_rt_on_default);
    					else
    						rt.setImageResource(R.drawable.ic_action_rt_off_default);
    					
    					
        				//Retweet
        				retw.setOnClickListener(new OnClickListener() {
        					public void onClick(View v) {
        						// TODO Auto-generated method stub
    							//System.out.println("AAAAAABB");
    							if (tweet_item.getUserID() == GlobalData.user_id)
    								return;
    							String message, button1;
    							// Get retweet value
    							int refav = Integer.parseInt(tweet_item.getRefav()) %10;
    							if (refav == 0){
    								message = "Retweet this to your followers ?";
    								button1 = "Retweet"; 
    							}
    							else{
    								message = "Undo this retweet ?";
    								button1 = "Undo";
    							}
    								
    							AlertDialog.Builder builder  = new AlertDialog.Builder(Twitter.this);
    							builder.setTitle("Retweet");
    							builder.setMessage(message);
    							builder.setPositiveButton(button1, new DialogInterface.OnClickListener() {						
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									String requestString;
    									int refav = Integer.parseInt(tweet_item.getRefav()) %10;
    									if (refav == 0){
    										requestString = ConnectionTwitter.SERVER_URL+"api/tweet/retweet?tweet_id="+tweet_item.getID();
    									}
    									else
    										requestString = ConnectionTwitter.SERVER_URL+"api/tweet/unretweet?tweet_id="+tweet_item.getID();
    									if (ConnectionTwitter.sendRequest(requestString) != null)
    									{
    										//Change Image Refav
    										if(refav == 0) //Retweet
    										{
    											if(tweet_item.getRefav().equals("0"))
    												tweet_item.setRefav("1");
    											if(tweet_item.getRefav().equals("10"))
    												tweet_item.setRefav("11");
    										}
    										else //UnRetweet
    										{
    											if(tweet_item.getRefav().equals("1"))
    												tweet_item.setRefav("0");
    											if(tweet_item.getRefav().equals("11"))
    												tweet_item.setRefav("10");											
    										}
    										//System.out.println(tweet_item.getRefav()+"|"+"AT");
        									tweet_item.setIsLongClick(false);
        									old_post = -1;
        									m_adapter.notifyDataSetChanged();										
    									}									
    								}
    							})
    							.setNeutralButton("Quote", new DialogInterface.OnClickListener() {						
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    		    						m_tweet_item.get(pos).setIsLongClick(false);
    		    						m_adapter.notifyDataSetChanged();
    		    						
    		    						String quote = m_tweet_item.get(pos).getContent();
    		    						quote = "\""+quote+"\"";
    		    						Intent quote_intent = new Intent(Twitter.this,NewTweetDialog.class);
    		    						Bundle bund = new Bundle();
    		    						bund.putString("mentions", quote);
    		    						bund.putString("tweet_id", m_tweet_item.get(pos).getID());
    		    						quote_intent.putExtras(bund);
    		    						startActivity(quote_intent);		
    		    						
    								}
    							})
    							.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									dialog.dismiss();
    								}
    							});
    							builder.show();   						
        					}
        				});     					
    					
    				}
    				
    			}
    			else
    			{
    				LinearLayout longlayout = (LinearLayout)v.findViewById(R.id.timeline_onlongclick);
    				LinearLayout onlayout = (LinearLayout)v.findViewById(R.id.timeline_mainparent);
    				
    				longlayout.setVisibility(View.GONE);
    				onlayout.setVisibility(View.VISIBLE); 
    				
    				RelativeLayout rtwed = (RelativeLayout)v.findViewById(R.id.retweeted_by_layout);
    				ImageView imgview = (ImageView)v.findViewById(R.id.timeline_avarta);
    				TextView fullname = (TextView)v.findViewById(R.id.timeline_fullname);
    				TextView username = (TextView)v.findViewById(R.id.timeline_username);
    				TextView content = (TextView)v.findViewById(R.id.timeline_content);
    				TextView time = (TextView)v.findViewById(R.id.timeline_time);
    				
    				ImageView refav = (ImageView)v.findViewById(R.id.timeline_refav);
    				
    				if(tweet_item.getRetweetedBy().equals(""))
    					rtwed.setVisibility(View.GONE);
    				else
    				{
    					TextView rtwedby = (TextView)v.findViewById(R.id.retweeted_by);
    					rtwedby.setText("Retweeted by "+tweet_item.getRetweetedBy());
    				}
    				
    				switch(getItemViewType(position))
    				{
    					case 0 : 
    						break;
    					case 1 :
    						refav.setImageResource(R.drawable.ic_dogear_rt);
    						break;
    					case 10 : 
    						refav.setImageResource(R.drawable.ic_dogear_fave);
    						break;
    					case 11:
    						refav.setImageResource(R.drawable.ic_dogear_both);
    						break;
    				}
    				
    				fullname.setText(tweet_item.getFullname());
    				username.setText("@"+tweet_item.getUsername());
    				content.setText(tweet_item.getContent());
    				time.setText(tweet_item.getCreatedTime());
    				GlobalData.imageLoader.DisplayImage(tweet_item.getAvatar(), imgview);
    				//imgview.setImageBitmap(ImageHelper.getRoundedCornerBitmap(tweet_item.getAvarta(), 5));
    			}
    		}
    		
    		return v;
    	}
    	
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.profile:
                // Change to activity Other Person Profile
                Intent profile = new Intent(Twitter.this, OtherPersonProfile.class);
                Bundle bundle = new Bundle();
                //bundle.putString("");
                startActivity(profile);
            case R.id.settings:
                System.out.println("settings");
                return true;
            case R.id.accounts:
                accountAction();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void accountAction() {
        // Remove cookie from settings
        SharedPreferences settings = getSharedPreferences(GlobalData.COKKIE_FILE, MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.remove(GlobalData.currentUser.getUser_id());
        if (settings.getString(GlobalData.DEFAULT_USER, "").equals(GlobalData.currentUser.getUser_id())){
            editor.remove(GlobalData.DEFAULT_USER);
        }
        editor.commit();

		// unregister google cloud messaging
		GCMRegistrar.unregister(this);

        // Go back to Start activity
        Intent startActivity = new Intent(Twitter.this, StartActivity.class);
        startActivity(startActivity);
        finish();
    }

	/**
	 * Handle when click share button
	 */
	private void shareAction(String content) {
		//create the send intent
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		//set the type
		shareIntent.setType("text/plain");
		//add a subject
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share");
		//build the body of the message to be shared
		String shareMessage = content;
		//add the message
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
		//start the chooser for sharing
		startActivity(Intent.createChooser(shareIntent,"Share"));
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 0)
		{
			if(data != null)
			{
				Bundle receive = data.getExtras();
				m_tweet_item.get(item_position_clicked - 1).setRefav(receive.getString("refav"));
				m_adapter.notifyDataSetChanged();
			}
		}
	}
	
}
